"""
@Author  : 康帅
@Time    : 2021/3/15 14:12
@Function: 单例模式实现三：装饰器的方法
"""


def singleton_decorator(cls, *args, **kwargs):
    """ 定义一个单例装饰器 """
    instance = {}

    def wrapper(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]

    return wrapper


@singleton_decorator
class Singleton:
    """ 使用单例装饰器装饰一个类 """

    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name


if __name__ == '__main__':
    tony = Singleton("Tony")
    jack = Singleton("Jack")
    print(tony.get_name(), jack.get_name())
    print("id(tony):", id(tony), "id(jack)", id(jack))
    print("tony == jack:", tony == jack)
